package gitapp.oschina.net.my_osc;

import android.app.Activity;

import java.util.Stack;

/**
 * 应用程序Activity管理类，用于Activity管理和应用程序退出
 * @author Tristan-Hou
 */
public class AppManager {

    private static AppManager instance;
    private static Stack<Activity> activityStack;

    public static AppManager getAppManager(){
        if (instance == null){
            instance = new AppManager();
        }
        return instance;
    }

    public void addActivity(Activity activity){
        if (activityStack == null){
            activityStack = new Stack<Activity>();
        }
        activityStack.push(activity);
    }

    public Activity currentActivity(){
        if (activityStack == null){
            return null;
        }
        return activityStack.lastElement();
    }

    public void finishActivity(){
        if (activityStack != null){
            Activity activity = activityStack.lastElement();
            finishActivity(activity);
        }
    }

    public void finishActivity(Activity activity){
        if (activity != null){
            activityStack.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    public void finishActivity(Class<?> cls){
        for (Activity activity:activityStack){
            if (activity.getClass().equals(cls)){
                finishActivity(activity);
            }
        }
    }

    public void finishAllActivity(){
        for (int i = 0; i < activityStack.size(); i++){
            if (activityStack.get(i) != null){
                Activity activity = activityStack.pop();
                if (!activity.isFinishing()){
                    activity.finish();
                }
            }
        }
        activityStack.clear();
    }

    public void AppExit(){
        finishAllActivity();
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    public void removeActivity(Activity activity){
        if (activity != null){
            activityStack.remove(activity);
        }
    }

}
